package com.biye.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.base.common.edu.entity.HatArea;
import com.base.common.edu.entity.HatCity;
import com.base.common.edu.entity.HatProvince;
import com.base.common.edu.mapper.ProvinceToAreaMapper;
import com.base.common.httpStatusCode.enumDefine.StatusCode;
import com.biye.api.service.HatPCAService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisCluster;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class HatPCAServiceImpl implements HatPCAService {

    @Resource
    private ProvinceToAreaMapper provinceToAreaMapper;

    @Autowired
    JedisCluster jedisCluster;

    /***
     * 使用类似于级联选择器
     * @return
     */
    @Override
    public JSONObject getPCA_json() {
        JSONObject json = new JSONObject();
        String msg = "暂无数据";
        int statusCode = StatusCode.Failure._statusCode;
        // 每个（省/市/区）都是一个对象，放在一个List里，初始化最外层省列表，数据结构适应ElementUI's Cascader(级联选择器)
        /*  eg. below
            [
                {
                    code: "370000",
                    name: "山东省",
                    children: [
                        {
                            code: "370200",
                            name: "青岛市",
                            children: [
                                {
                                    code: "370205",
                                    name: "四方区",
                                },
                                {
                                    code: "370211",
                                    name: "黄岛区",
                                }
                            ]
                        },
                        {
                            code: "370100",
                            name: "济南市",
                        }
                    ]
                },
                {
                    code: "450000",
                    name: "广西壮族自治区",
                }
            ]
         */
//        List<String> nan = new ArrayList<>();
        /*
(省)广东省@440000(市)东莞市@441900 下(区)为空
(省)广东省@440000(市)中山市@442000 下(区)为空
(省)台湾省@710000 下(市)为空
(省)香港特别行政区@810000 下(市)为空
(省)澳门特别行政区@820000 下(市)为空
         */
        // 判断缓存里有木有装有省市区json的键值对儿，有就直接取了返回。没有这个键值对就从数据库取值后填充，有效期1小时
        String judge_pca_json_exist = jedisCluster.get("pca_json");
        if ( judge_pca_json_exist != null ) {
            // 从redis取出字符串，还原成对象
            List<Map<String, Object>> provinces_copy;
            Gson to_obj = new Gson();
            provinces_copy = to_obj.fromJson(judge_pca_json_exist, List.class);
            json.put("pca", provinces_copy);
            msg = "查询成功";
            statusCode = StatusCode.Success._statusCode;
            json.put("msg", msg);
            json.put("statusCode", statusCode);
            json.put("dataFrom", "redisCache");
            return json;
        }
        List<Map<String, Object>> provinces = null;
        List<Map<String, Object>> cities = null;
        List<Map<String, Object>> areas = null;
        // 一、首先拼接省数据
        boolean flag = false;
        List<HatProvince> hatProvinces = provinceToAreaMapper.queryAllProvinces();
        if ( hatProvinces.size() > 0 ){
            provinces = new ArrayList<>();
            Map<String, Object> temp_province = null;
            // 迭代所有省
            for ( HatProvince hp : hatProvinces ){
                temp_province = new HashMap<>();
                cities = new ArrayList<>();
                Map<String, Object> temp_city = null;
                // 二、从省里迭代所有区
                List<HatCity> hatCities = provinceToAreaMapper.queryAllCityByProvinceName(hp.getProvince_id());
//                if ( hatCities.size() == 0 )
//                    nan.add("(省)" + hp.getProvince_name() + "@" + hp.getProvince_id() + " 下(市)为空");
                for( HatCity hc : hatCities) {
                    temp_city = new HashMap<>();
                    areas = new ArrayList<>();
                    Map<String, Object> temp_area = null;
                    // 三、遍历市下的所有区，并把区装入市对象
                    List<HatArea> hatAreas = provinceToAreaMapper.queryAllAreaByCityName(hc.getCity_id());
//                    if ( hatAreas.size() == 0 )
//                        nan.add( "(省)" + hp.getProvince_name() + "@" + hp.getProvince_id() +"(市)" + hc.getCity_name() + "@" + hc.getCity_id() + " 下(区)为空");
                    for( HatArea ha : hatAreas ) {
                        temp_area = new HashMap<>();
                        temp_area.put("value", ha.getArea_id());
                        temp_area.put("label", ha.getArea_name());
                        areas.add(temp_area);
                    }
                    // 把该市的信息和对应区信息装入市List
                    temp_city.put("value", hc.getCity_id());
                    temp_city.put("label", hc.getCity_name());
                    temp_city.put("children", areas);
                    cities.add(temp_city);
                }
                // 把该省的信息和对应的市及区信息装入省List
                temp_province.put("value", hp.getProvince_id());
                temp_province.put("label", hp.getProvince_name());
                temp_province.put("children", cities);
                provinces.add(temp_province);
            }
            json.put("pca", provinces);
            // 转换成字符串装入redis
            Gson redis_gson = new Gson();
            String jsonStr = redis_gson.toJson(provinces);
            jedisCluster.set("pca_json", jsonStr);
            jedisCluster.expire("pca_json", 60*60);
            flag = true;
        }
        if ( flag ) {
            msg = "查询成功";
            statusCode = StatusCode.Success._statusCode;
            json.put("dataFrom", "oracleDB");
        }
        // 打印出省市下为空的市区
//        if ( nan.size() > 0 )
//            for( String c : nan )
//                System.out.println(c);
        json.put("msg", msg);
        json.put("statusCode", statusCode);
        return json;
    }

}
